package io;

import javax.imageio.IIOException;
import javax.swing.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class GetChannel {

    private static String name = "data.txt";
    private static final int BSIZE = 1024;
    public static void main(String[] args) {
        try (FileChannel channel = new FileOutputStream(name).getChannel();) {
            channel.write(ByteBuffer.wrap("fjldsajfl".getBytes()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try (FileChannel fc = new RandomAccessFile(name,"rw").getChannel();
        ){
            ByteBuffer buffer = ByteBuffer.wrap("sdfdsf".getBytes());
            fc.position(fc.size());
            fc.write(buffer);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try (FileChannel fc = new FileInputStream(name)
                .getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
            fc.read(buffer);
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.write(buffer.get());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.flush();
    }
}
